package com.jxj.util;

import com.jxj.entity.gen.Adminuser;
import com.jxj.entity.gen.TUser;
import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @Author Cambria
 * @creat 2021/8/14 11:09
 */
public class JWTUtil {
    //签名密钥，实际部署需要改
    private static final String SECRET = "asdk";
    private static final long EXPIRESAT = 7*24*60*60*1000L;

    /**
     * JWT签名工具
     * @param user 登录用户
     * //@param orgId 组织管理员用户所在组织的id，数据库里似乎没给，非组织管理员用户定为-1
     * @return token
     */
    public static String sign(TUser user) {
        String token = Jwts.builder()
                .setSubject("ResruitUser")
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRESAT))
                .claim("userId", user.getId())
                .claim("orgId", user.getOid())
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }

    public static String sign(Adminuser user) {
        String token = Jwts.builder()
                .setSubject("ResruitUser")
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRESAT))
                .claim("userId", user.getId())
                .claim("orgId", user.getOid())
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }

    /**
     * 获取用户id
     * @param token 用户token
     * @return 用户id
     */
    public static int getUserId(String token) {
        if(StringUtils.isEmpty(token)) return -1;

        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        Integer userId = (Integer)claims.get("userId");
        return (int) claims.get("userId");
    }

    /**
     * 获取用户所管理的组织id
     * @param token 用户token
     * @return 组织id
     */
    public static int getOrgId(String token) {

        if(StringUtils.isEmpty(token)) return -1;

        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return (int) claims.get("orgId");
    }

}
